package com.tanhua.api.mongo;

import com.tanhua.domain.mongo.FollowUser;
import com.tanhua.domain.mongo.Video;
import com.tanhua.domain.vo.PageBeanVo;
import org.apache.dubbo.config.annotation.Service;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@Service
public class VideoApiImpl implements VideoApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private IdService idService;

    @Override
    public PageBeanVo findByPage(Integer pageNum, Integer pageSize) {
        // 分页查询
        Integer index = (pageNum - 1) * pageSize;
        Query query = new Query().with(Sort.by(Sort.Order.desc("created"))).skip(index).limit(pageSize);

        List<Video> videoList = mongoTemplate.find(query, Video.class);

        long counts = mongoTemplate.count(query, Video.class);
        return new PageBeanVo(pageNum, pageSize, counts, videoList);
    }

    @Override
    public void save(Video video) {
        // 指定小视频发布时间和vid
        video.setCreated(System.currentTimeMillis());
        video.setVid(idService.getNextId("video"));
        // 保存
        mongoTemplate.save(video);
    }

    @Override
    public void saveFollowUser(FollowUser followUser) {
        // 指定关注时间
        followUser.setCreated(System.currentTimeMillis());
        // 保存
        mongoTemplate.save(followUser);
    }

    @Override
    public void removeFollowUser(Long userId, Long followUserId) {
        // 指定删除条件
        Query query = Query.query(
                Criteria.where("userId").is(userId)
                        .and("followUserId").is(followUserId)
        );
        // 删除
        mongoTemplate.remove(query, FollowUser.class);
    }

    @Override
    public PageBeanVo findUserByPage(Integer pageNum, Integer pageSize, Long userId) {
        // 构建条件
        Query query = new Query(Criteria.where("userId").is(userId))
                .with(Sort.by(Sort.Order.desc("created")))
                .skip((pageNum - 1) * pageSize).limit(pageSize);
        List<Video> list = mongoTemplate.find(query, Video.class);
        long count = mongoTemplate.count(query, Video.class);

        return new PageBeanVo(pageNum, pageSize, count, list);
    }

    @Override
    public Video findById(String videoId) {
        return mongoTemplate.findById(new ObjectId(videoId), Video.class);
    }

    @Override
    public List<Video> findByVids(List<Long> vidList) {
        Query query = Query.query(Criteria.where("vid").in(vidList));
        return mongoTemplate.find(query, Video.class);
    }
}
